using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Sedna.Core.Controller.Configurations
{
	/// <summary>
	/// Summary description for DataGridColumnInboundControlPropertySetterTranslator.
	/// </summary>
	public class DataGridColumnInboundControlPropertySetterTranslator: IDataTranslator
	{
		private string propertyName;
		private bool convertToString=false;

		public bool ConvertToString
		{
			set { convertToString = value; }
		}

		public string PropertyName
		{
			set { propertyName = value; }
		}

		public object Translate(Control control, object value)
		{
			return Translate(control, value, null);
		}

		public object Translate(Control control, object value, Type targetType)
		{
			if (control==null||propertyName==null)
			{
				return null;
			}
			Type controlType=control.GetType();
			PropertyInfo property=controlType.GetProperty(propertyName, BindingFlags.Public|BindingFlags.Instance|BindingFlags.Static|BindingFlags.IgnoreCase, null, null, new Type[]{}, null);
			if (property==null)
			{
				throw new ControllerConfigurationException(String.Format("property with name {0} not found in class {1}", propertyName, controlType));
			}

			MethodInfo setter=property.GetSetMethod();
			if (setter==null)
			{
				throw new ControllerConfigurationException(String.Format("property with name {0} has no setter", propertyName));
			}

			setter.Invoke(control, new object[]{convertToString?(value!=null?value.ToString():""):value});
			return null;
		}
	}
}
